package com.jwpdk.appframework.data;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;

public class DataMap extends HashMap implements IData {

	private static final long	serialVersionUID	= -529653701132982551L;

	/**
	 * get object
	 * @param name
	 * @param def
	 * @return Object
	 */
	public Object get(String name, Object def) {
		Object value = get(name);
		return value == null ? def : value;
	}

	/**
	 * get string
	 * @param name
	 * @return String
	 */
	public String getString(String name) {
		Object value = get(name);
		return value == null ? null : value.toString();
	}

	/**
	 * get string
	 * @param name
	 * @return String
	 */
	public String getString(String name, String defaultValue) {
		return get(name,defaultValue).toString();
	}

	/**
	 * get int
	 * @param name
	 * @return int
	 */
	public int getInt(String name) {
		return getInt(name,0);
	}

	/**
	 * get int
	 * @param name
	 * @param defaultValue
	 * @return int
	 */
	public int getInt(String name, int defaultValue) {
		String value = getString(name,"");
		return "".equals(value) ? defaultValue : Integer.parseInt(value);
	}

	/**
	 * get double
	 * @param name
	 * @return double
	 */
	public double getDouble(String name) {
		return getDouble(name,0);
	}

	/**
	 * get double
	 * @param name
	 * @param defaultValue
	 * @return double
	 */
	public double getDouble(String name, double defaultValue) {
		String value = getString(name,"");
		return "".equals(value) ? defaultValue : Double.parseDouble(value);
	}

	/**
	 * get boolean
	 * @param name
	 * @return boolean
	 */
	public boolean getBoolean(String name) {
		return getBoolean(name,false);
	}

	/**
	 * get boolean
	 * @param name
	 * @param defaultValue
	 * @return boolean
	 */
	public boolean getBoolean(String name, boolean defaultValue) {
		String value = getString(name,"");
		return "".equals(value) ? defaultValue : Boolean.valueOf(value).booleanValue();
	}

	@SuppressWarnings("unchecked")
	@Override
	public String toString() {
		StringBuffer sBuffer = new StringBuffer();
		Iterator keySet = this.keySet().iterator();
		String name = "";
		sBuffer.append("{");
		while ( keySet.hasNext() ) {
			name = (String) keySet.next();
			sBuffer.append(name).append(":");
			if ( this.get(name) != null )
				sBuffer.append(this.get(name).toString()).append(",");
			else
				sBuffer.append("NULL").append(",");
		}
		name = sBuffer.toString();
		name = name.substring(0,name.length() - 1);
		name = name.length() > 0 ? name + "}" : name;
		return name;
	}

	@SuppressWarnings("unchecked")
	public String[] getNames() {
		String[] names = (String[]) keySet().toArray(new String[0]);
		Arrays.sort(names);
		return names;
	}

	public char getChar(String name) {

		return getChar(name,'0');
	}

	public char getChar(String name, char defaultValue) {
		String value = getString(name,"").toUpperCase();
		return "".equals(value) ? defaultValue : value.toCharArray()[0];
	}
}